package com.cp.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.cp.common.exception.BusinessException;
import com.cp.common.result.R;
import com.cp.common.result.ResponseEnum;
import com.cp.core.pojo.entity.Dict;
import com.cp.core.pojo.dto.ExcelDictDTO;
import com.cp.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author ming
 * @since 2022-07-27
 */
@RestController
@RequestMapping("/admin/core/dict")
@Api(tags = "数据字典管理")
@Slf4j
//@CrossOrigin
public class AdminDictController {
    @Resource
    private DictService dictService;
    @ApiOperation("excel数据的批量导入")
    @PostMapping("/import")
    public R batchImport(@ApiParam(value = "数据字典文件",required = true)
                             @RequestParam("file") MultipartFile file ){
        try {
            dictService.importData(file.getInputStream());
            return R.ok().message("数据批量导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }

    }
    @ApiOperation("excel数据导出")
    @GetMapping("/export")
    public void export (HttpServletResponse response)throws IOException{
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("mydict","UTF-8").replaceAll("\\+","%20");
        response.setHeader("Content-disposition","attachment;fileName*=utf-8''"+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.excelData());
    }
    @ApiOperation("延迟展示数据字典")
    @GetMapping("/listByParentId/{parentId}")
    public R listByParentId(@ApiParam(value = "上级节点id",required = true) @PathVariable Long parentId){
      List<Dict> dictList = dictService.listByParentId(parentId);
      return R.ok().data("list",dictList);
    }

}

